package com.antoco.operation.bigscreen.exceptions;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(MethodArgumentNotValidException.class)
  public ResponseEntity<Map<String, Object>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {

    Map<String, Object> resMap = new HashMap<String, Object>();

    List<ObjectError> errors = e.getBindingResult().getAllErrors();
    List<String> messages = formatAllErrorMessages(errors);

    resMap.put("msg", messages);

    return new ResponseEntity<Map<String, Object>>(resMap, HttpStatus.UNPROCESSABLE_ENTITY);
  }

  @ExceptionHandler(ConstraintViolationException.class)
  public ResponseEntity<Map<String, Object>> handleConstraintViolationException(ConstraintViolationException e) {
    Map<String, Object> resMap = new HashMap<String, Object>();
    List<String> errorMsg = e.getConstraintViolations().stream()
            .map(ConstraintViolation::getMessage)
            .collect(Collectors.toList());

    resMap.put("msg", errorMsg);

    return new ResponseEntity<Map<String, Object>>(resMap, HttpStatus.UNPROCESSABLE_ENTITY);
}

  // 拼接验证报错信息
  private List<String> formatAllErrorMessages(List<ObjectError> errors){
      List<String> errorMessageLists = new ArrayList<String>();
      errors.forEach(error -> errorMessageLists.add(error.getDefaultMessage()));
      return errorMessageLists;
  }
}
